package com.jrx.anytxn.param.job.cutover.step;

import com.jrx.anytxn.caffeine.service.ICaffeineMsgPublisher;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.base.BtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 日切清空业务日期缓存设置
 *
 * @author : zhenghaopu
 * 2019/12/6
 */
@Service
public class CutoverEndListener implements JobExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(CutoverEndListener.class);

    @Autowired
    ICaffeineMsgPublisher caffeineMsgPublisher;

    @Resource
    private BtBatchStatusMapper btBatchStatusMapper;

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;

    @Override
    public void beforeJob(JobExecution jobExecution) {

    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        caffeineMsgPublisher.sendClearAllMsg();//清除机构缓存
        record();//记录日终批次信息
    }

    /**
     * 记录日终批次到批次状态信息表
     */
    private void record(){
        PrOrganizationTable org =
                extPrOrganizationTableMapper.selectByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
        BtBatchStatus btBatchStatus = new BtBatchStatus();
        try {
            btBatchStatus.setId(segmentService.getId(Constant.BT_BATCH_STATUS_ID));//id
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
        }
        btBatchStatus.setBatchStatus(Constant.BATCH_SATTUS_2);//状态 2 完成
        btBatchStatus.setBusinessDate(org.getNextProcessingDate());//当前业务日期
        btBatchStatus.setJobName(Constant.CUTOVER_END);//批处理名称
        btBatchStatus.setTenantId(org.getTenantId());//租户id
        btBatchStatus.setUpdateBy(Constant.DEFAULT_USER);
        btBatchStatus.setRecordVersionNumber(Constant.VERSION_NUMBER);//初始版本号
        btBatchStatusMapper.insertSelective(btBatchStatus);
    }

}
